//################################
// 版权所有：中国农业银行软件开发中心
// 系统名称：移动办公应用-手机版
// 文件名称：myGesturePassword.js
// 创建时间：2016年10月29日
// 创建人员：Panda
// 功能说明：手势密码设置
//################################

'use strict';

import React, {Component} from 'react';
import {
    View,
    Text,
    StyleSheet,
    Dimensions,
    TouchableOpacity,
    Image,
    InteractionManager,
    // Switch,
} from 'react-native';

import {
    Colors,
    FontSizes,
    UIConstants,
} from '../../common';

import GesturePassword from '../../components/pandaGesturePassword';
import Switch from '../../components/pandaSwitch';
import Images from '../../images';

import LocalStorage from '../../utils/storageUtil';
import {toastTip} from '../../utils/toastTipUtil';

const WINDOW_WIDTH = Dimensions.get('window').width;
const WINDOW_HEIGHT = Dimensions.get('window').height;

class MyGesturePassword extends Component {
    constructor(props) {
        super(props);

        this._renderDescription = this._renderDescriptionFunc.bind(this);
        this._renderActions = this._renderActionsFunc.bind(this);
        this._onFinish = this._onFinishFunc.bind(this);
        this._onReset = this._onResetFunc.bind(this);
        this.onBackPress = this.onBackPressFunc.bind(this);

        this._cachedPassword = '';
        this.counts = 4;

        this.state = {
            isWarning: false,
            tips: UIConstants.my.gesturePasswordSetting,
            isGesturePasswordPanelShow: props.route.data.hasGesturePassword,
            switchTips: props.route.data.hasGesturePassword ? UIConstants.my.gesturePasswordOff : UIConstants.my.gesturePasswordOn,
        };
    }

    onBackPressFunc() {
        const {navigatorRoot} = this.props;
        InteractionManager.runAfterInteractions(() => {
            navigatorRoot.pop();
        });
    }

    _renderThumbnails () {
        let thumbnails = []
        for (let i = 0; i < 9; i++) {
            let active = ~this.state.password.indexOf(i)
            thumbnails.push((
                <View
                    key={'thumb-' + i}
                    style={[
                        {width: 8, height: 8, margin: 2, borderRadius: 8, },
                        active ? {backgroundColor: '#00AAEF'} : {borderWidth: 1, borderColor: '#A9A9A9'}
                    ]}
                />
            ))
        }
        return (
            <View style={{width: 38, flexDirection: 'row', flexWrap: 'wrap'}}>
                {thumbnails}
            </View>
        )
    }

    _renderDescriptionFunc() {
        return (
            <View style={{height: 158, paddingBottom: 10, justifyContent: 'flex-end', alignItems: 'center',}}>
                {this._renderThumbnails()}
                <Text
                    style={{fontFamily: '.HelveticaNeueInterface-MediumP4', fontSize: 14, marginVertical: 6, color: this.state.messageColor}}>{this.state.message}</Text>
            </View>
        )
    }

    _renderActionsFunc() {
        return (
            <View
                style={{position: 'absolute', bottom: 0, flex:1, justifyContent: 'space-between', flexDirection: 'row', width: Dimensions.get('window').width, }}>
                <Button
                    style={{ margin: 10, height: 40, justifyContent: 'center', }}
                    textStyle={{fontSize: 14, color: '#A9A9A9'}}>
                    Forget password
                </Button>
                <Button
                    style={{ margin: 10, height: 40, justifyContent: 'center', }}
                    textStyle={{fontSize: 14, color: '#A9A9A9'}}>
                    Login other accounts
                </Button>
            </View>
        )
    }

    verifyGesturePassword(password) {
        let length = password.length;
        if (length < 4) {
            let isWarning = true;
            this.setState({
                isWarning,
                tips: UIConstants.my.gesturePasswordSettingTooShort,
            });
            setTimeout(() => {
                this.setState({
                    tips: UIConstants.my.gesturePasswordSetting,
                });
            }, 1500);
            return false;
        }
        return true;
    }

    saveGesturePassword() {
        LocalStorage.getUserList((userList) => {this.gotUserList(userList)});
    }

    gotUserList(userList) {
        if (userList === null) {
            userList = [];
        }

        // 找到最近一次登录的用户信息
        for (let i = 0;i < userList.length;i++) {
            let user = userList[i];

            if (user.lastLogined) {
                userList[i].gesturePwd = this._cachedPassword;
                LocalStorage.saveUserList(userList, (isOk) => {this.saveGesturePasswordDone(isOk)});
                break;
            }
        }
    }

    saveGesturePasswordDone(isOk) {
        if (this._cachedPassword === '') {
            return;
        }
        
        if (isOk) {
            let isWarning = false;
            this.setState({
                isWarning,
                // tips: UIConstants.my.gesturePasswordSettingSuccess,
            });

            this.showToast(UIConstants.my.gesturePasswordSettingSuccess);

            //倒数几秒之后退回前页
            this.startCountDownTimer();
        }
        else {
            this.showToast(UIConstants.my.saveGesturePasswordError);
            this.setState({
                tips: UIConstants.my.gesturePasswordSetting,
            });
        }
    }

    showToast(msg) {
        toastTip(msg, 'long');
    }

    startCountDownTimer() {
        if (this.counts === 0) {
            clearTimeout(this.timer);
            const {navigatorRoot} = this.props;
            navigatorRoot.pop();

            return;
        }

        this.counts = this.counts - 1;

        let self = this;

        this.timer = setTimeout(() => {
            self.setState({
                tips: UIConstants.my.gesturePasswordSettingCountDownTips.replace('{counts}', this.counts),
            });
            self.startCountDownTimer();
        }, 1000);
    }

    _onFinishFunc(password) {
        let verifyResult = this.verifyGesturePassword(password);

        if (!verifyResult) {
            return;
        }

        if (this._cachedPassword === '') {
            this._cachedPassword = password;
            this.setState({
                tips: UIConstants.my.gesturePasswordSettingAgain,
            });
            return;
        }

        if (password === this._cachedPassword) {
            this.saveGesturePassword();
        }
        else {
            this._cachedPassword = '';
            let isWarning = true;
            this.setState({
                isWarning,
                tips: UIConstants.my.gesturePasswordSettingError,
            });

            setTimeout(() => {
                this.setState({
                    tips: UIConstants.my.gesturePasswordSetting,
                });
            }, 1500);
        }
        // alert('password is ' + password)
    }

    _onResetFunc() {
        let isWarning = false;
        this.setState({
            isWarning,
        });
    }

    onSwitchStateChange(state) {
        this.setState({
            isGesturePasswordPanelShow: state,
            switchTips: state ? UIConstants.my.gesturePasswordOff : UIConstants.my.gesturePasswordOn,
        });

        if (!state) {
            this._cachedPassword = '';

            this.saveGesturePassword();
        }
    }

    render() {
        return (
            <View style={{flex: 1, backgroundColor: '#FFFFFFA0'}}>
                {
                    this.state.isGesturePasswordPanelShow ? 
                    <View style={styles.container}>
                        <GesturePassword
                            pointBackgroundColor={'#F4F4F4'}
                            isWarning={this.state.isWarning}
                            color={'#A9A9A9'}
                            activeColor={'#37B9D0'}
                            warningColor={'red'}
                            warningDuration={1500}
                            allowCross={true}
                            topComponent={this._renderDescription}
                            bottomComponent={this._renderActions}
                            onFinish={this._onFinish}
                            onReset={this._onReset}
                        />
                    </View>
                    :
                    null
                }
                {
                    this.state.isGesturePasswordPanelShow ? 
                    <View style={styles.tips}>
                        <View style={styles.innertipsview}>
                            <Text style={styles.tipstext}>
                                {this.state.tips}
                            </Text>
                        </View>
                    </View>
                    :
                    null
                }
                <View style={styles.header}>
                    <TouchableOpacity style={styles.headerback} onPress={this.onBackPress}>
                        <Image source={Images.Back} style={styles.headerbackicon} resizeMode={Image.resizeMode.contain} />
                        <Text style={styles.headerbacktext}>{UIConstants.my.back}</Text>
                    </TouchableOpacity>
                    <Text style={styles.headertext}>
                        {UIConstants.my.gesturePasswordPageHeader}
                    </Text>
                    <TouchableOpacity style={styles.headerback} disabled={true}>
                        <Image source={Images.Back} style={[styles.headerbackicon, {opacity: 0}]} resizeMode={Image.resizeMode.contain} />
                        <Text style={[styles.headerbacktext, {opacity: 0}]}>{UIConstants.zhsoi.back}</Text>
                    </TouchableOpacity>
                </View>
                <View style={styles.switchview}>
                    <Text style={styles.switchtext}>{this.state.switchTips}</Text>
                    <View style={{alignItems: 'center', justifyContent: 'center', paddingRight: 16}}>
                        <Switch ref={(ref) => {this.switch = ref}} active={this.state.isGesturePasswordPanelShow} buttonRadius={14} switchHeight={29} switchWidth={50} onChangeState={(state) => {this.onSwitchStateChange(state)}} />
                    </View>
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    switchview: {
        position: 'absolute',
        width: WINDOW_WIDTH,
        backgroundColor: 'white',
        marginTop: 80,
        flexDirection: 'row',
        borderTopWidth: 0.5,
        borderTopColor: 'rgba(0, 0, 0, 0.1)',
        borderBottomWidth: 0.5,
        borderBottomColor: 'rgba(0, 0, 0, 0.1)',
    },
    switchtext: {
        marginTop: 14,
        marginBottom: 14,
        marginLeft: 30,
        fontSize: 20,
        color: 'black',
        flex: 1,
    },
    header: {
        height: 60,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        borderBottomWidth: 1,
        borderBottomColor: Colors.soiHeaderBorder,
        position: 'absolute',
        width: WINDOW_WIDTH,
        backgroundColor: Colors.appHeaderBackground,
        // backgroundColor: 'white',
        // borderColor: 'green',
        // borderWidth: 20,
    },
    headerback: {
        flexDirection: 'row',
        marginBottom: -12,
        alignItems: 'center',
        padding: 8,
    },
    headerbackicon: {
        width: 20,
        height: 20,
    },
    headerbacktext: {
        fontSize: FontSizes.soiHeaderBack,
        color: Colors.appHeaderText,
    },
    headertext: {
        flex: 1,
        fontSize: FontSizes.soiHeader,
        color: Colors.appHeaderText,
        textAlign: 'center',
        alignSelf: 'center',
        marginBottom: -12,
    },
    container: {
        position: 'absolute',
        width: WINDOW_WIDTH,
        height: WINDOW_HEIGHT,
        alignItems: 'center',
        justifyContent: 'center',
        // backgroundColor: '#FFFFFF80',
        // marginTop: 200,
        // borderWidth: 4,
        // borderColor: 'blue',
    },
    headerview: {
        position: 'absolute',
        width: WINDOW_WIDTH,
        height: 60,
        backgroundColor: 'white',
        borderColor: 'green',
        borderWidth: 20,
    },
    tips: {
        position: 'absolute',
        width: WINDOW_WIDTH,
        height: 100,
        marginTop: 140,
        alignItems: 'center',
        justifyContent: 'center',
        // borderWidth: 5,
        // borderColor: 'red',
    },
    innertipsview: {
        alignSelf: 'center',
        alignItems: 'center',
        justifyContent: 'center',
    },
    tipstext: {
        fontSize: 26,
        color: 'black',
    },
    // buttonview: {
    //     position: 'absolute',
    //     top: WINDOW_HEIGHT - 120,
    //     width: WINDOW_WIDTH,
    //     height: 80,
    //     backgroundColor: 'yellow',
    // },
});

export default MyGesturePassword;